/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import utilities.ZipUtil;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimplePlanetAdmin;
import jsonHelper.SimpleUniverse;
import service.Audio;
import service.MumuUser;
import service.MumuUserFacadeREST;
import service.Photo;
import service.PhotoCollection;
import service.Planet;
import service.PlanetFacadeREST;
import service.Tag;
import service.Universe;
import service.UniverseFacadeREST;
import service.Video;
import utilities.ReadSmtp;
/**
 *
 * @author andrew
 */
public class AdminUniverseServlet extends HttpServlet {

    @EJB
    private MumuUserFacadeREST userManager;
    @EJB
    private UniverseFacadeREST universeManager;
    @EJB
    private PlanetFacadeREST planetManager;
    
    private Session session;

    // <editor-fold desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        Gson gson = new Gson();

        String idSelectedUserString = request.getParameter("selectedUser");

        String idSelectedUniverseString = request.getParameter("selectedUniverse");


        // se esiste il parametro "selectedUser" ritorna lista universi di quell'utente
        if (idSelectedUserString != null) {
            int idSelectedUser = Integer.parseInt(idSelectedUserString);

            ArrayList<SimpleUniverse> arraySimpleUniverse = new ArrayList<SimpleUniverse>();

            MumuUser selectedUser = userManager.find(idSelectedUser);

            Collection<Universe> collUniverse = selectedUser.getUniverseCollection();

            Iterator<Universe> itUniverse = collUniverse.iterator();
            while (itUniverse.hasNext()) {
                Universe universe = itUniverse.next();

                SimpleUniverse simpleUniverse = new SimpleUniverse();
                simpleUniverse.setIdUniverse(universe.getIdUniverse());
                simpleUniverse.setDescriptionUniverse(universe.getDescription());
                simpleUniverse.setNameUniverse(universe.getName());
                simpleUniverse.setNumberPlanets(universe.getPlanetCollection().size());
                simpleUniverse.setIsReady(universe.getIsReady());
                // assegno anche il creatore dell'universo
                Collection<MumuUser> collCreator = universe.getMumuUserCollection();
                Iterator<MumuUser> itCeator = collCreator.iterator();
                while (itCeator.hasNext()) {
                    MumuUser creator = itCeator.next();
                    simpleUniverse.setCreatorName(creator.getNameSurname());
                    simpleUniverse.setIdCreator(creator.getIdUser());
                }


                if (universe.getIsValidated()) {
                    simpleUniverse.setIsValidated(1);
                } else {
                    simpleUniverse.setIsValidated(0);
                }

                arraySimpleUniverse.add(simpleUniverse);

            }

            String arrayGson = gson.toJson(arraySimpleUniverse);

            // restituzione JSON
            out.println(arrayGson);
            out.close();

        } else if (idSelectedUniverseString != null) {
            // se esiste "selectedUniverse" ritorna lista pianeti associati
            System.out.println("DENTRO AD ADMIN");
            int idSelectedUniverse;
            HttpSession httpsession = request.getSession();
            if(httpsession.getAttribute("idUniverse") != null && idSelectedUniverseString.equals(""))
                idSelectedUniverse = (Integer)(httpsession.getAttribute("idUniverse"));
            else
                idSelectedUniverse = Integer.parseInt(idSelectedUniverseString);

            ArrayList<SimplePlanetAdmin> arraySimplePlanetAdmin = new ArrayList<SimplePlanetAdmin>();

            Universe universe = universeManager.find(idSelectedUniverse);

            Collection<Planet> collPlanet = universe.getPlanetCollection();

            Iterator<Planet> itPlanet = collPlanet.iterator();

            while (itPlanet.hasNext()) {

                Planet planet = itPlanet.next();

                SimplePlanetAdmin simplePlanetAdmin = new SimplePlanetAdmin(planet.getIdPlanet(), planet.getReferenceName(), planet.getShortLabel(),
                        planet.getTitle1(), planet.getTitle2(), planet.getTitle3());

                simplePlanetAdmin.setInfoPlanet(planet.getDescription());
                simplePlanetAdmin.setIsControlled(planet.getControlled());
                simplePlanetAdmin.setEmotionalFilter(planet.getEmotionalFilter());
                
                // prendo i path delle foto
                Collection<PhotoCollection> collPhotoCollection = planet.getPhotoCollectionCollection();
                Iterator<PhotoCollection> itPhotoCollection = collPhotoCollection.iterator();
                while (itPhotoCollection.hasNext()) {

                    PhotoCollection photoCollection = itPhotoCollection.next();
                    Collection<Photo> collPhoto = photoCollection.getPhotoCollection();

                    if (photoCollection.getIsHappy()) {
                        // gestione foto felici
                        simplePlanetAdmin.setDescriptionPhotoHappy(photoCollection.getDescription());
                        Iterator<Photo> itPhoto = collPhoto.iterator();
                        while (itPhoto.hasNext()) {
                            Photo photo = itPhoto.next();
                            simplePlanetAdmin.addInPathPhotoHappy(photo.getPathPhoto());
                        }
                    } else {
                        // gestione foto tristi
                        simplePlanetAdmin.setDescriptionPhotoSad(photoCollection.getDescription());
                        Iterator<Photo> itPhoto = collPhoto.iterator();
                        while (itPhoto.hasNext()) {
                            Photo photo = itPhoto.next();
                            simplePlanetAdmin.addInPathPhotoSad(photo.getPathPhoto());
                        }
                    }
                }

                // prendo i path audio
                Collection<Audio> collAudio = planet.getAudioCollection();
                Iterator<Audio> itAudio = collAudio.iterator();
                while (itAudio.hasNext()) {
                    Audio audio = itAudio.next();
                    if (audio.getIsHappy()) {
                        //gestione audio happy
                        simplePlanetAdmin.setAudioHappyPath(audio.getPathAudio());
                        simplePlanetAdmin.setAudioHappyDescription(audio.getDescription());
                        simplePlanetAdmin.setAudioHappyTitle(audio.getTitle());
                    } else {
                        // gestione audio sad
                        simplePlanetAdmin.setAudioSadPath(audio.getPathAudio());
                        simplePlanetAdmin.setAudioSadDescription(audio.getDescription());
                        simplePlanetAdmin.setAudioSadTitle(audio.getTitle());
                    }
                }


                // prendo i path video
                Collection<Video> collVideo = planet.getVideoCollection();
                Iterator<Video> itVideo = collVideo.iterator();
                while (itVideo.hasNext()) {
                    Video video = itVideo.next();
                    if (video.getIsHappy()) {
                        //gestione video happy
                        simplePlanetAdmin.setVideoHappyPath(video.getPathVideo());
                        simplePlanetAdmin.setVideoHappyDescription(video.getDescription());
                        simplePlanetAdmin.setVideoHappyTitle(video.getTitle());
                    } else {
                        // gestione video sad
                        simplePlanetAdmin.setVideoSadPath(video.getPathVideo());
                        simplePlanetAdmin.setVideoSadDescription(video.getDescription());
                        simplePlanetAdmin.setVideoSadTitle(video.getTitle());
                    }
                }
                
                Collection<Tag> collTags = planet.getTagCollection();
                Iterator<Tag> itTags = collTags.iterator();
                while (itTags.hasNext()){
                    simplePlanetAdmin.addInTags(itTags.next().getDescription());
                }
                
                arraySimplePlanetAdmin.add(simplePlanetAdmin);
                
                
            }

            String arrayGson = gson.toJson(arraySimplePlanetAdmin);

            // restituzione JSON
            out.println(arrayGson);
            out.close();

        } else {
            // senza nessun parametro torna tutti gli universi del sistema

            ArrayList<SimpleUniverse> arraySimpleUniverse = new ArrayList<SimpleUniverse>();

            List<Universe> listUniverse = universeManager.findAll();

            Iterator<Universe> itUniverse = listUniverse.iterator();
            while (itUniverse.hasNext()) {
                Universe universe = itUniverse.next();
                SimpleUniverse simpleUniverse = new SimpleUniverse();
                simpleUniverse.setIdUniverse(universe.getIdUniverse());
                simpleUniverse.setDescriptionUniverse(universe.getDescription());
                simpleUniverse.setNameUniverse(universe.getName());
                simpleUniverse.setNumberPlanets(universe.getPlanetCollection().size());
                simpleUniverse.setIsReady(universe.getIsReady());
                // assegno anche il creatore dell'universo
                Collection<MumuUser> collCreator = universe.getMumuUserCollection();
                Iterator<MumuUser> itCeator = collCreator.iterator();
                while (itCeator.hasNext()) {
                    MumuUser creator = itCeator.next();
                    simpleUniverse.setCreatorName(creator.getNameSurname());
                    simpleUniverse.setIdCreator(creator.getIdUser());
                }


                if (universe.getIsValidated()) {
                    simpleUniverse.setIsValidated(1);
                } else {
                    simpleUniverse.setIsValidated(0);
                }
                
                

                arraySimpleUniverse.add(simpleUniverse);
            }

            String arrayGson = gson.toJson(arraySimpleUniverse);

            // restituzione JSON
            out.println(arrayGson);
            out.close();
        }

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        final ReadSmtp readSmtp = new ReadSmtp(request);

        if (action.equals("accept")) {
            String idUniverseString = request.getParameter("idUniverse");
            int idUniverse = Integer.parseInt(idUniverseString);

            String idCreatorString = request.getParameter("idCreator");
            int idCreator = Integer.parseInt(idCreatorString);

            Universe universe = universeManager.find(idUniverse);

            // universo accettato
            universe.setIsValidated(true);
            universe.setIsReady(0);
            universeManager.edit(universe);
            
            // notifica tramite mail che l'universo è stato accettato
            MumuUser userForMail = userManager.find(idCreator);
                        
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( readSmtp.getAuth_username(), "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userForMail.getMail()));
                message.setSubject("UniverseCreator: il tuo universo "+universe.getName()+" è stato pubblicato");
                String content = "Gentile " + userForMail.getNameSurname() + ",<br/><br/>"
                        + "L'universo da te creato, avente <br/>"
                        + "<br/>"
                        + "Nome: " + universe.getName() + "<br/>"
                        + "Descrizione : " + universe.getDescription() + "<br/><br/>"
                        + "&egrave; stato validato e pubblicato.<br/>"
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
            
            // creazione del file zip
            doZipFile(request.getServletContext().getRealPath("/") + "Universes/" + idUniverse);
            
            // cancellazione in filesystem dello zip vecchio avatar
            File directoryAvatar = new File(request.getServletContext().getRealPath("/") + "Universes/avatar.zip");

            //verifica se la directory esiste
            if (!directoryAvatar.exists()) {
                System.out.println("DirectoryAvatar zip does not exist.");
            } else {

                try {
                    delete(directoryAvatar);
                } catch (Exception e) {
                }
            }
            
            // zip della cartella avatar
            doZipFile(request.getServletContext().getRealPath("/") + "Universes/avatar");
            
            // creazione suggerimenti in base ai tag
            //createRouteTagBased(idUniverse);

        } else if (action.equals("reject")) {
            // universo rigettato e quindi va cancellato

            String idUniverseString = request.getParameter("idUniverse");
            int idUniverse = Integer.parseInt(idUniverseString);

            String idCreatorString = request.getParameter("idCreator");
            int idCreator = Integer.parseInt(idCreatorString);

            Universe universe = universeManager.find(idUniverse);

            MumuUser user = userManager.find(idCreator);

            Collection<Universe> collUniverse = user.getUniverseCollection();
            Iterator<Universe> itUniverse = collUniverse.iterator();
            while (itUniverse.hasNext()) {
                Universe u = itUniverse.next();
                if (u.getIdUniverse() == idUniverse) {
                    itUniverse.remove();
                }
            }
            user.setUniverseCollection(collUniverse);
            userManager.edit(user);

            universeManager.remove(universe);

            // cancellazione in filesystem della cartella Universo associata
            File directory = new File(request.getServletContext().getRealPath("/") + "Universes/" + idUniverse);

            //verifica se la directory esiste
            if (!directory.exists()) {
                System.out.println("Directory does not exist.");
            } else {

                try {
                    delete(directory);
                } catch (Exception e) {
                }
            }
            
            
            // cancellazione zip della cartella Universo associata
            File directoryZip = new File(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+".zip");

            //verifica se la directory esiste
            if(!directoryZip.exists()){
               System.out.println("DirectoryZip does not exist.");
            } else {
               try{ 
                   delete(directoryZip);
               }catch(Exception e){}
            }

            System.out.println("Done. Universe Zip file has been deleted");

            System.out.println("Deleted universe " + idUniverse);
            
            // notifica tramite mail che l'universo è stato accettato
            MumuUser userForMail = userManager.find(idCreator);
                        
            Properties props = new Properties();
            props.put("mail.smtp.host", readSmtp.getSmtp_address());
            props.put("mail.smtp.socketFactory.port", readSmtp.getSmtp_port());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", readSmtp.getAuth());
            props.put("mail.smtp.port", readSmtp.getSmtp_port());

            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // email address e password
                            return new PasswordAuthentication(readSmtp.getAuth_username(), readSmtp.getAuth_password());
                        }
                    });

            try {
                InternetAddress from = new InternetAddress( readSmtp.getAuth_username(), "UniverseCreator" );
                
                Message message = new MimeMessage(session);
                message.setFrom(from);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userForMail.getMail()));
                message.setSubject("UniverseCreator: il tuo universo "+universe.getName()+" è stato eliminato");
                String content = "Gentile " + userForMail.getNameSurname() + ",<br/><br/>"
                        + "L'universo da te creato, avente <br/>"
                        + "<br/>"
                        + "Nome: " + universe.getName() + "<br/>"
                        + "Descrizone : " + universe.getDescription() + "<br/><br/>"
                        + "&egrave; stato rifiutato e cancellato dal sistema.<br/>"
                        + "<br/><br/><br/>"
                        + "<i>Staff di UniverseCreator</i>"
                        + "<br/><br/><br/>"
                        + "Non rispondere, messaggio generato in automatico da UniverseCreator.<br/>";
                message.setContent(content, "text/html");
                Transport.send(message);
            } catch (Exception e) {
                System.err.println(e.getCause());
            }
            
        } else if (action.equals("checked")) {

            String checkedString = request.getParameter("checked");
            int check = Integer.parseInt(checkedString);

            String idPlanetString = request.getParameter("idPlanet");
            int idPlanet = Integer.parseInt(idPlanetString);

            if (check == 1) {
                Planet p = planetManager.find(idPlanet);
                p.setControlled(1);
                planetManager.edit(p);
            } else {
                Planet p = planetManager.find(idPlanet);
                p.setControlled(0);
                planetManager.edit(p);
            }
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private static void delete(File file) throws IOException {

        if (file.isDirectory()) {

            //directory è vuota, quindi si può cancellare
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : " + file.getAbsolutePath());
            } else {

                //lista di tutte le sottodirectory contenute
                String files[] = file.list();

                for (String temp : files) {
                    //construttore file
                    File fileDelete = new File(file, temp);

                    //cancellazione ricorsiva
                    delete(fileDelete);
                }

                //controllo se directory è vuota e in caso affermativo la rimuovo
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : " + file.getAbsolutePath());
                }
            }

        } else {
            //se è file lo si cancella
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }

    private void doZipFile(String pathFolderToZip) throws IOException{
        
        ZipUtil zipper = new ZipUtil();
        
        File directoryToZip = new File(pathFolderToZip);
        String zipFilePath = pathFolderToZip + ".zip";
        
        List<File> listFiles = new ArrayList<File>(1);
        listFiles.add(directoryToZip);  
        
        zipper.compressFiles(listFiles, zipFilePath);
    }   

    private void createRouteTagBased(int idUniverseAccepted) {
        
        // prendo i pianeti dell'ultimo universo accettato
        
        
        
    }
    
}
